package com.xk.account;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class accountDaoImpl {
    List<Account> accounts = new ArrayList<>();

    //添加数据
    public int insert(Account account) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DBUtils.getConnetcion();
            preparedStatement = connection.prepareStatement("insert into account(cardNo,password,name,balance)values (?,?,?,?);");
            preparedStatement.setString(1, account.getCard());
            preparedStatement.setString(2, account.getPassword());
            preparedStatement.setString(3, account.getNAME());
            preparedStatement.setDouble(4, account.getBalance());
            int result = preparedStatement.executeUpdate();
            if (result == 1) {
                System.out.println("新增成功！");
            } else
                System.out.println("新增失败！");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
        return 0;
    }

    //删除数据
    public int delete(String cardNo) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DBUtils.getConnetcion();
            preparedStatement = connection.prepareStatement("delete from account where cardNo=?;");
            preparedStatement.setString(1, cardNo);
            int result = preparedStatement.executeUpdate();
            if (result == 1) {
                System.out.println("删除成功！");
            } else
                System.out.println("删除失败！");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
        return 0;
    }

    //修改数据
    public int update(Account account) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        int result;
        try {
            connection = DBUtils.getConnetcion();
            preparedStatement = connection.prepareStatement("update account set password=?,name=?,balance=? where cardNo=?;");
            preparedStatement.setString(1, account.getPassword());
            preparedStatement.setString(2, account.getNAME());
            preparedStatement.setDouble(3, account.getBalance());
            preparedStatement.setString(4, account.getCard());
            result = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
        if (result == 1) {
            System.out.println("修改成功！");
        } else
            System.out.println("修改失败！");
        return result;
    }

    //查单条数据
    public Account select(String cardNo) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = DBUtils.getConnetcion();
            preparedStatement = connection.prepareStatement("select * from account where cardNo=?;");
            preparedStatement.setString(1, cardNo);
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {//遍历数据库中的每一列数据
                Account account = new Account();
                account.setCard(resultSet.getString("cardNo"));
                account.setPassword(resultSet.getString("password"));
                account.setNAME(resultSet.getString("name"));
                account.setBalance(resultSet.getDouble("balance"));
                return account;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
        return null;
    }

    //查所有数据
    public List<Account> selectAll() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = DBUtils.getConnetcion();
            preparedStatement = connection.prepareStatement("select * from account;");
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {//遍历数据库中的每一列数据
                Account account = null;
                String cardNo1 = resultSet.getString("cardNo");
                String password = resultSet.getString("password");
                String name = resultSet.getString("name");
                double balance = resultSet.getDouble("balance");
                account = new Account(cardNo1, password, name, balance);
                accounts.add(account);
            }
            return accounts;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
    }

    /**
     * 转账功能
     * 事务处理
     */
    public Account transfer(Account account, double transferAmount) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        String cardNoFrom = "6002"; // 转出卡号
        String cardNoTo = "2003";   // 转入卡号

        try {
            // 1. 从数据库中获取所有账户信息
            List<Account> allAccounts = selectAll();

            // 2. 使用 Stream API 检查转出账户是否存在
            boolean fromExists = allAccounts.stream().anyMatch(a -> a.getCard().equals(cardNoFrom));

            // 3. 使用 Stream API 检查转入账户是否存在
            boolean toExists = allAccounts.stream().anyMatch(a -> a.getCard().equals(cardNoTo));

            // 4. 如果转出账户不存在，则输出错误信息并返回
            if (!fromExists) {
                System.out.println("卡号尾号为" + cardNoFrom + "的账户不存在，无法转账");
                return account;
            }

            // 5. 如果转入账户不存在，则输出错误信息并返回
            if (!toExists) {
                System.out.println("卡号尾号为" + cardNoTo + "的账户不存在，无法转账");
                return account;
            }

            // 6. 获取数据库连接
            connection = DBUtils.getConnetcion();

            // 7. 关闭自动提交，开启事务
            connection.setAutoCommit(false);

            // 8. 查询转出账户的余额
            String queryBalanceSQL = "select balance from account where cardNo = ?";
            preparedStatement = connection.prepareStatement(queryBalanceSQL);
            preparedStatement.setString(1, cardNoFrom);
            resultSet = preparedStatement.executeQuery();

            double currentBalance = 0.0;
            if (resultSet.next()) {
                currentBalance = resultSet.getDouble("balance");
            }

            // 9. 检查余额是否足够
            if (currentBalance < transferAmount) {
                System.out.println("余额不足，无法完成转账！");
                return account;
            }

            // 10. 执行减钱操作
            String updateBalanceSQL = "update account set balance = balance - ? where cardNo = ?";
            preparedStatement = connection.prepareStatement(updateBalanceSQL);
            preparedStatement.setDouble(1, transferAmount);
            preparedStatement.setString(2, cardNoFrom);
            int result1 = preparedStatement.executeUpdate();
            System.out.println("成功修改转出账户 " + result1 + " 行");

            // 11. 执行加钱操作
            preparedStatement.setDouble(1, transferAmount); // 注意：这里是加钱，所以应该是正数
            preparedStatement.setString(2, cardNoTo);
            int result2 = preparedStatement.executeUpdate();
            System.out.println("成功修改转入账户 " + result2 + " 行");

            // 12. 提交事务
            connection.commit();

        } catch (SQLException e) {
            // 13. 如果出现异常，则回滚事务
            if (connection != null) {
                try {
                    connection.rollback();
                } catch (SQLException rollbackEx) {
                    System.err.println("回滚事务失败：" + rollbackEx.getMessage());
                }
            }
            // 14. 抛出运行时异常
            throw new RuntimeException("转账操作失败：" + e.getMessage(), e);
        } finally {
            // 15. 释放资源：ResultSet, PreparedStatement, Connection
            DBUtils.closeAll(connection, preparedStatement, resultSet);
        }

        return account;
    }


}

